|
|
 |
|
|
|
|
36:
37: Set mvarpSoleInstance = New Customer
38: MsgBox New Customer object created
39: End Function |
|
|
|
|
|
|
|
|
The property pSoleInstance was declared as Friend Static so that only those objects within the project can access the Customer class instance. Notice the method createSoleInstance. This is the key enforcer in your class. In it, you allow only one instance of the Customer class via the SetNew syntax. Of course, more than one instance of Customer can be created outside your class, which means that it must be mutually agreed that the one instance created (in your case, theCustomer) will be the only broker for creating instances of the Customer class. Nevertheless, you could have designed this method as in Listing 3.2. |
|
|
|
|
|
|
|
|
LISTING 3.2. THE MODIFIEDcreateSoleInstanceMETHOD. |
|
|
|
 |
|
|
|
|
1: Public Static Function createSoleInstance() As Customer
2: Attribute createSoleInstance.VB_UserMemId = 0
3: Dim m_InstanceCount As Byte 'local copy
4: If m_InstanceCount = 1 Then
5: MsgBox Only one instance allowed
6: Exit Function
7: End If
8:
9: Set mvarpSoleInstance = New Customer
10: MsgBox New Customer object created
11: m_InstanceCount = 1
12: End Function |
|
|
|
|
|
|
|
|
In the createSoleInstance method in Listing 3.1, you used the TypeName method to test whether your late-bound object is of the type Customer. When the class is first initialized, it is of the type Object. Therefore, the check for the TypeName will be False on the first invocation of createSoleInstance. However, because it is the first time, the object will be set to something other than Object, namely Customer. Thus, when a second SetNew Customer is encountered, the TypeName test will be True, meaning that additional instances can't be allowed. In Listing 3.2, on the other hand, a static instance counter is used to limit the instance count to one. Either way is an effective pattern for ensuring only one instance exists. |
|
|
|
|
|